﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CFrame.Common;
using System.Net;
using System.Net.Sockets;
using CFrame.Tools;

/*
 * 脚本功能：网络管理器
 * 编写日期：2018.12.13
 * 编写人：HYZ
 */
namespace CFrame.Manager
{
    public class NetManager : BaseManager
    {
        //public NetManager(GameMiddle game) : base(game) { }

        /// <summary>
        /// 收到消息的回调
        /// </summary>
        public NetCallback messageCallback;

        private string ipAddress = "127.0.0.1";
        public string IP
        {
            set
            {
                ipAddress = value;
            }
        }

        private int port = 8080;
        public int Port
        {
            set
            {
                port = value;
            }
        }

        private Socket client;

        private Message message = new Message();

        public override void OnDestroy()
        {
            try
            {
                if(client != null)
                {
                    client.Close();
                    client = null;
                }
            }catch(Exception e)
            {
                Debuger.LogError("关闭客户端连接异常 --> " + e);
            }
        }

        public override void OnInit()
        {
            client = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            try
            {
                client.Connect(ipAddress, port);

                BeginReceive();

            }catch(Exception e)
            {
                Debuger.LogWarning("无法连接到服务器端,请检查网络 --> 【" + ipAddress + ":" + port + "】 ：" + e);
            }
        }

        public override void OnUpdate()
        {
            
        }

        /// <summary>
        /// 异步消息接收
        /// </summary>
        private void BeginReceive()
        {
            client.BeginReceive(message.Data, message.StartIndex, message.RemainSize, SocketFlags.None,ReceiveCallback, null);
        }

        /// <summary>
        /// 收到消息处理
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                if (client == null || client.Connected == false)
                    return;

                int count = client.EndReceive(ar);
                //解析消息
                message.ReadMessage(count, OnProcessDataCallback);
                //继续接收消息
                BeginReceive();

            }catch(Exception e)
            {
                Debuger.Log("ReceiveCallback Error:" + e);
            }
        }

        //消息回调处理
        private void OnProcessDataCallback(int actionCode,string data)
        {
            Debuger.Log(actionCode + " --> " + data);
            if(messageCallback!= null)
            {
                messageCallback(actionCode, data);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        public void SendRequest(int requestCode,int actionCode,string data)
        {
            byte[] bytes = Message.PackData(requestCode, actionCode, data);
            client.Send(bytes);
        }
    }
}
